<?php
//抓取地址
$url = 'http://product.weather.com.cn/alarm/grepalarm_cn.php?_=' . getMillisecond();

//抓取内容
$content = file_get_contents($url);


//截取获取到的内容
$data = substr($content, 14, -1);

//配置预警类型
$kindObj = json_decode('{"01":"台风","02":"暴雨","03":"暴雪","04":"寒潮","05":"大风","06":"沙尘暴","07":"高温","08":"干旱","09":"雷电","10":"冰雹","11":"霜冻","12":"大雾","13":"霾","14":"道路结冰","91":"寒冷","92":"灰霾","93":"雷雨大风","94":"森林火险","95":"降温","96":"道路冰雪","97":"干热风","98":"空气重污染","99":"低温","51":"海上大雾","52":"雷暴大风","53":"持续低温","54":"浓浮尘","55":"龙卷风","56":"低温冻害","57":"海上大风","58":"低温雨雪冰冻","59":"强对流","60":"臭氧","61":"大雪","62":"强降雨","63":"强降温","64":"雪灾","65":"森林（草原）火险","66":"雷暴","67":"严寒","68":"沙尘","69":"海上雷雨大风","70":"海上雷电","71":"海上台风","72":"低温"}', true);

//配置预警等级
$gradeObj = json_decode('{"01":"蓝色","02":"黄色","03":"橙色","04":"红色","05":"白色"}', true);

//json解析获得的数据
$data = json_decode($data, true);

//确定需要的内容
$data = $data['data'];
//var_dump($data);


//配置数据库
$servername = "";//服务器地址
$username = "";//账号
$password = "";//密码
$dbname = "";//库名

//连接数据库
$conn = new mysqli ($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
$b = [];
$body = "";

//需要检测多个城市的时候反复调用alarma函数就可以。
alarma("甘肃省白银市");
//alarma("江西省南昌市");
//alarma("四川省泸州市");
//alarma("四川省宜宾市");

//如果$body 就是邮件正文有内容就发邮件。
if (!empty($body)) {
    mailx($body);
}

function alarma($city)
{
    global $data, $kindObj, $gradeObj, $conn, $body;//声明变量
    foreach ($data as $k => $v) {
        if ($v[0] == $city) {
            $b[] = $v[1];
            //预警文件名
            $fname = $v[1];
            //截取类型+等级,后面生成ID用
            $types = explode(".", explode("-", $fname)[2])[0];

            //截取预警等级
            $kind = substr($types, 0, 2);
            //截取类型
            $level = substr($types, 2);

            //转译成汉字
            $kind = $kindObj["$kind"];
            $level = $gradeObj["$level"];

            //截取发布时间
            $time = explode('-', $fname)[1];
            
            //输出收到的预警信息内容
            echo date('Y年m月d日 H时i分 ', strtotime($time)) . $city . " 发布" . $kind . $level . '预警 <a href="http://www.weather.com.cn/alarm/newalarmcontent.shtml?file=' . $fname . '" target="_blank">' . $v[1] . '</a>';
            
            //查询这条预警信息是否入库
            $select = "SELECT * FROM `fname` WHERE `fname` =' $fname'";
            $result = mysqli_query($conn, $select);


            if (mysqli_num_rows($result) == 0) {//没入库操作
                echo "需要处理 -> "; //如果没有记录的回显
                $id = $time . $types;//生成ID 就是用时间和预警类型、等级代码生成一串数字

                //抓取预警信息正文
                $URL = 'http://product.weather.com.cn/alarm/webdata/'.$fname.'?_=' . getMillisecond();

                //抓取内容并json解析预警信息
                $alarma_info = json_decode(substr(file_get_contents($URL), 14), true);

                //记录入库
                $sql = "INSERT INTO `fname` (id , type, level , fname , status ) VALUES ('$id' , '$kind' , '$level' , '$fname','1')";
                if ($conn->query($sql) === TRUE) {
                    echo "已记录 -> ";
                    echo "打包记录到邮件正文<br>\n";
                    return $body .= $alarma_info["ISSUECONTENT"] . ' 文件地址：<a href="http://www.weather.com.cn/alarm/newalarmcontent.shtml?file=' . $fname . '" target="_blank">' . $fname . '</a><br>';
                } else {
                    echo "数据库错误: " . $sql . "<br>" . $conn->error;
                }
            } else {
                echo "不处理<br>\n"; //已入库回显
            }
        }
    }
}

function mailx($bodyy)
{

    $title = date('Y年m月d日 H时i分') . '收到气象预警';//邮件标题
    header("content-type:text/html;charset=utf-8");
    ini_set("magic_quotes_runtime", 0);
    require 'mailer/class.phpmailer.php';
    try {
        $mail = new PHPMailer(true);
        $mail->IsSMTP();
        $mail->CharSet = 'UTF-8';//设置邮件的字符编码，这很重要，不然中文乱码
        $mail->SMTPAuth = true;//开启认证
        $mail->Port = 587;//SMTP端口
        $mail->Host = "smtp.qq.com";//SMTP服务器地址
        $mail->Username = "";//SMTP账号
        $mail->Password = "";//SMTP密码
        //$mail->IsSendmail(); //如果没有sendmail组件就注释掉，否则出现“Could  not execute: /var/qmail/bin/sendmail ”的错误提示
        $mail->AddReplyTo("", "");//回复地址，格式为 "邮件地址", "名字"
        $mail->From = "";//发件人地址
        $mail->FromName = "";//显示的发件人名字 可空
        $to = "";//收件人地址，只能1个
        $mail->AddAddress($to);
        $mail->Subject = $title;//邮件标题
        $mail->Body = $bodyy;//邮件正文
        $mail->AltBody = "To view the message, please use an HTML compatible email viewer!";//当邮件不支持html时备用显示，可以省略。我这里设置与正文一致
        $mail->WordWrap = 80;// 设置每行字符串的长度
        //$mail->AddAttachment("f:/test.png");  //可以添加附件
        $mail->IsHTML(true);//HTML邮件标记
        $mail->Send();//执行发送命令

        echo "发送成功<br>\n";

    } catch (phpmailerException $e) {
        echo "邮件发送失败：" . $e->errorMessage() . "<br>\n";
    }


}

//毫秒级时间戳
function getMillisecond()
{
    list($s1, $s2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
